package oceanwiki.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import oceanwiki.controller.UserController;
import oceanwiki.entity.Category;
import oceanwiki.entity.Ebook;
import oceanwiki.entity.User;
import oceanwiki.exception.BusinessException;
import oceanwiki.exception.BusinessExceptionCode;
import oceanwiki.mapper.UserMapper;
import oceanwiki.req.UserLoginReq;
import oceanwiki.req.UserQueryReq;
import oceanwiki.req.UserSaveReq;
import oceanwiki.resp.*;
import oceanwiki.service.IUserService;
import oceanwiki.util.CopyUtil;
import oceanwiki.util.SnowFlake;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张飞
 * @since 2024-09-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    @Resource
    private SnowFlake snowFlake;

    @Override
    public PageResp<UserQueryResp> listByName(UserQueryReq req) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();

        queryWrapper.like(StringUtils.isNotBlank(req.getName()), "name", req.getName());
        queryWrapper.or().like(StringUtils.isNotBlank(req.getLoginName()), "login_name", req.getLoginName());

        //创建分页参数
        Page<User> page = new Page<>(req.getPage(), req.getSize());
        page = this.baseMapper.selectPage(page, queryWrapper);


        List<UserQueryResp> resps = CopyUtil.copyList(page.getRecords(), UserQueryResp.class);

        PageResp<UserQueryResp> pageResp = new PageResp<>();
        pageResp.setList(resps);
        pageResp.setTotal(page.getTotal());

        return pageResp;
    }

    @Override
    public void save(UserSaveReq req) {
        User e = CopyUtil.copy(req, User.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            //新增
            // 判断用户名是否已经存在
            User one = this.baseMapper.selectOne(new QueryWrapper<User>().eq("login_name", req.getLoginName()));

            if (ObjectUtils.isEmpty(one)) {
                //雪花算法生成id
                long id = snowFlake.nextId();
                e.setId(id);
                this.baseMapper.insert(e);
            } else {
                throw new BusinessException(BusinessExceptionCode.user_login_name_exist);
            }


        } else {
            //更新
            e.setLoginName(null); //避免绕过前端，修改登录名
            this.baseMapper.updateById(e);
        }
    }

    @Override
    public void delete(Long id) {
        this.baseMapper.deleteById(id);
    }

    @Override
    public List<UserQueryResp> all() {
        // 使用sort列进行排序
        List<User> users = this.baseMapper.selectList(new QueryWrapper<User>().orderByAsc(" "));

        List<UserQueryResp> list = CopyUtil.copyList(users, UserQueryResp.class);

        return list;
    }

    @Override
    public UserLoginResp login(UserLoginReq req) {
        //根据用户名查询用户信息
        User user = this.baseMapper.selectOne(new QueryWrapper<User>().eq("login_name", req.getLoginName()));
        if (ObjectUtils.isEmpty(user)) {
            LOG.info("用户名不存在，{}", req.getLoginName());
            throw new BusinessException(BusinessExceptionCode.login_user_error);

        } else {
            if (user.getPassword().equals(req.getPassword())) {

                //登录成功
                UserLoginResp userLoginResp = CopyUtil.copy(user, UserLoginResp.class);
                return userLoginResp;
            } else {
                //密码不正确
                LOG.info("密码不正确，请输入密码{}, 数据库密码{}", req.getPassword(), user.getPassword());
                throw new BusinessException(BusinessExceptionCode.login_user_error);
            }
        }
    }
}
